package cn.com.edaily.api.auth.controller;

import cn.com.edaily.auth.enumeration.LoginResultEnum;
import cn.com.edaily.auth.facade.AuthFacade;
import cn.com.edaily.auth.request.LoginRequestDTO;
import cn.com.edaily.auth.request.RegisterRequestDTO;
import cn.com.edaily.auth.utils.RsaKeyFactory;
import cn.com.edaily.common.Response;
import cn.com.edaily.common.RsaKey;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class AuthController {

	@Autowired
	private AuthFacade authFacade;

	/**
	 * @param requestDTO
	 * @return Response<?>
	 * @Description: 注册
	 * @author chenwb
	 * @date 2020/1/30 14:52
	 */
	@RequestMapping("/register")
	public Response<?> register(@RequestBody RegisterRequestDTO requestDTO) {
		return authFacade.register(requestDTO);
	}

	/**
	 * @return Response<String>
	 * @Description: 获取公钥
	 * @author chenwb
	 * @date 2020/1/30 15:58
	 */
	@RequestMapping(value = "/getPublicKey", method = RequestMethod.GET)
	public Response<RsaKey> getPublicKey() {
		return Response.success(RsaKeyFactory.getInstance());
	}

	/**
	 * @Description: 登录接口
	 * @author chenwb
	 * @date 2020/2/1 21:07
	 * @param requestDTO 登录请求dto
	 * @return Response<String> 登录结果
	 */
	@RequestMapping("/login")
	public Response<String> Login(@RequestBody LoginRequestDTO requestDTO) {
		try {
			authFacade.Login(requestDTO);
		} catch (UnknownAccountException u) {
			return Response.error(LoginResultEnum.NOTEXSIST.getCode(), LoginResultEnum.NOTEXSIST.getText(), "");
		} catch (AuthenticationException a) {
			return Response.error(LoginResultEnum.AUTHWRONG.getCode(), LoginResultEnum.AUTHWRONG.getText(), "");
		}
		return Response.success(LoginResultEnum.SUCCESS.getCode(), LoginResultEnum.SUCCESS.getText(), "");
	}

	/**
	 * @Description: 登出
	 * @author chenwb
	 * @date 2020/2/1 21:07
	 * @return Response<String> 登出结果
	 */
	@RequestMapping("/logout")
	public Response<String> logout() {
		//销毁会话
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return Response.success("10000", "登出成功", "");
	}
}
